//
//  ZTTabBar.m
//  BeidouMall
//
//  Created by qie on 16/3/29.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "ZTTabBar.h"

#define tabbarHight 49.0

@interface ZTTabBar ()

@property (nonatomic, weak) UIButton *centerBtn;
@property (nonatomic, weak) UILabel *addrLabel;

@end

@implementation ZTTabBar

@dynamic delegate;

- (void)setAddrName:(NSString *)addrName {
    dispatch_async(dispatch_get_main_queue(), ^{// 更新UI操作必须在主线程
        self.addrLabel.text = addrName;
    });
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        UIButton *centerBtn = [[UIButton alloc] init];
        //[centerBtn setBackgroundImage:[UIImage imageNamed:@"centerBtn"] forState:UIControlStateNormal];
        
        centerBtn.size = CGSizeMake(kScreen_Width / 5 + 15.0, tabbarHight - 5.0);
        [centerBtn addTarget:self action:@selector(centerBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:centerBtn];
        
        UIImageView *addrImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"centerBtn"]];
        addrImgView.frame = CGRectMake(0, 4, 16, 17);
        addrImgView.centerX = centerBtn.centerX;
        [centerBtn addSubview:addrImgView];
        
        UILabel *addrLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(addrImgView.frame) + 3, centerBtn.width, 20)];
        addrLabel.text = _addrName;
        addrLabel.font = [UIFont boldSystemFontOfSize:14.0];
        addrLabel.textAlignment = NSTextAlignmentCenter;
        addrLabel.textColor = RGBColor(255, 255, 255);
        addrLabel.backgroundColor = RGBColor(83, 83, 83);
        [centerBtn addSubview:addrLabel];
        
        self.addrLabel = addrLabel;
        self.centerBtn = centerBtn;
    }
    return self;
}

- (void)centerBtnClick {
    if ([self.delegate respondsToSelector:@selector(tabBarDidClickCenterButton:)]) {
        [self.delegate tabBarDidClickCenterButton:self];
    }
}

/**
 *  想要重新排布系统控件subview的布局，推荐重写layoutSubviews，在调用父类布局后重新排布。
 */
- (void)layoutSubviews {
    [super layoutSubviews];
    // 设置中间button的位置
    self.centerBtn.centerX = self.width * 0.5;
    self.centerBtn.centerY = self.height * 0.5;
    // 设置其他tabbarButton的frame
    CGFloat tabBarButtonW = self.width / 5;
    CGFloat tabBarIndex = 0;
    for (UIView *child in self.subviews) {
        Class class = NSClassFromString(@"UITabBarButton");
        if ([child isKindOfClass:class]) {
            child.x = tabBarIndex * tabBarButtonW;
            child.width = tabBarButtonW;
            
            tabBarIndex++;
            if (tabBarIndex == 2) {// 中间button跳过
                tabBarIndex++;
            }
        }
    }
}

@end
